#! /usr/bin/env node
import { readFileSync, readdirSync } from "fs";
import { join, dirname } from "path";
import { convert } from "./Main";
import { JsonReader } from "./convert/reader/JsonReader";
import { getAbsolutePath, pathData } from "./utils/PathUtil";
import { SettingUtil } from "./utils/SettingUtil";

// console.log("---1111---");
export var processArg: any = {};
for (let i = 2; i < process.argv.length; i++) {
    let str = process.argv[i];
    if (str[0] == "-") str = str.substr(1);
    let arr = str.split("=");
    processArg[arr[0]] = arr[1] || 1;
}
// console.log("---2222---", processArg);
// console.log(command.length, command);
pathData.root = __dirname;
if (processArg["init"]) {
    SettingUtil.createTablecJson(process.cwd())
} else if (processArg["help"] || processArg["h"]) {
    showHelpStr();
} else if (processArg["config"] || processArg["c"]) {
    // console.log("---a---");

    let path = processArg["config"] || processArg["c"];
    if (typeof path != "string") {
        // console.log("---b---");
        path = join(process.cwd());
        let files = readdirSync(path);
        let jsonNames = files.filter(f => f.indexOf('.json') >= 0);
        new JsonReader().read(join(path, jsonNames[0]), null, (res) => {
            convert(res, path);
        });
    } else {
        // console.log("---c---");
        let tp = getAbsolutePath(path, process.cwd());
        let headPath = dirname(tp);
        new JsonReader().read(tp, null, (res) => {
            convert(res, headPath);
        });
    }
} else if (processArg["version"] || processArg["v"]) {
    let verUrl = join(__dirname, '../package.json');
    let verJson = JSON.parse(readFileSync(verUrl).toString())
    console.log(verJson.version);
} else {
    showHelpStr();
}


function showHelpStr() {
    let verUrl = join(__dirname, '../package.json');
    let verJson = JSON.parse(readFileSync(verUrl).toString())
    console.log('version:', verJson.version);
    console.log('\n');
    console.log("Usage: tablec [options]\n");
    console.log("Options:");
    console.log("   -c={filepath}, -config={filepath}               filepath作为配置文件路径导出");
    console.log("   -c, -config                                     从运行脚本的目录寻找json文件作为配置导出");
    console.log("   -h, -help                                       显示帮助");
    console.log("   -v, -version                                    显示当前版本");
    console.log('\n');

}

